<script setup>
import { NButton, NIcon } from 'naive-ui'
import { withModifiers } from 'vue'

const tableLoading = ref(false)
const tableColumns = ref([
  {
    type: 'selection',
  },
  {
    title: '序号',
    key: 'index',
    render: (_, index) => {
      return `${index + 1}`
    },
    resizable: true,
  },
  {
    title: 'Title',
    key: 'title',
    resizable: true,
    sorter: (rowA, rowB) => rowA.title.length - rowB.title.length,
  },
  {
    title: 'Length',
    key: 'length',
    resizable: true,
    sorter: (rowA, rowB) => rowA.length - rowB.length,
  },
  {
    title: 'Action',
    key: 'actions',
    render(row) {
      return h(
        NButton,
        {
          tertiary: true,
          size: 'small',
          onClick: withModifiers(() => handleTableEdit(row), ['stop']),
        },
        {
          icon: () => h(NIcon, () => h('div', { class: 'i-ri:edit-line' })),
          default: () => '编辑',
        },
      )
    },
    resizable: true,
  },
])
const tableData = ref([
  { title: 'Wonderwall', length: '5', key: 0 },
  { title: 'Don\'t Look Back in Anger', length: '6', key: 1 },
  { title: 'Champagne Supernova', length: '3', key: 2 },
])
const checkedRowKeys = ref([])

const page = ref(1)
const pageSize = ref(10)

const showModal = ref(false)
const modalTitle = ref('')
const formRef = ref(null)
const model = ref(cloneModal())
const rules = {
  title: { required: true, trigger: 'blur', message: '请输入 title' },
  length: { required: true, trigger: 'blur', message: '请输入 length' },
}

function handlePage(v) {
  page.value = v
}

function handlePageSize(v) {
  pageSize.value = v
}

function rowProps(row) {
  return {
    onClick: (e) => {
      // TODO 🧐 已知2.37.0版本中 row-prop和selection 有冲突 点击checkbox会触发row-props点击
      if (e.target.className !== 'n-checkbox-box__border') {
        const { key } = row

        const index = checkedRowKeys.value.indexOf(key)

        if (!~index)
          checkedRowKeys.value.push(key)
        else
          checkedRowKeys.value.splice(index, 1)
      }
    },
  }
}

function handleTableEdit(row) {
  modalTitle.value = '编辑'
  model.value = row
  showModal.value = true
}

function handleDelete() {
  if (!checkedRowKeys.value.length)
    return window.$message.warning('请选择需要删除的数据')

  window.$dialog.warning({
    title: '提示',
    content: '是否删除数据',
    positiveText: '确定',
    negativeText: '取消',
    autoFocus: false,
    onPositiveClick: () => {
      window.$message.loading('删除中')
    },
  })
}

function handleAdd() {
  modalTitle.value = '新增'
  showModal.value = true
}

// TODO 😭 可恶 naiveUI没有重置表单API
function cloneModal() {
  return {
    title: null,
    length: null,
  }
}

function handleAfterLeave() {
  formRef.value?.restoreValidation()
  model.value = cloneModal()
}

async function handleSubmit() {
  await formRef.value?.validate()
  window.$message.success('新增成功')
  showModal.value = false
}
</script>

<template>
  <div flex="~ col" gap="y-8px">
    <n-card size="small">
      <n-form
        :model="model"
        :show-feedback="false"
        label-placement="left"
        size="small"
      >
        <n-grid :x-gap="8">
          <n-form-item-gi label="title：" path="title" span="4">
            <n-input v-model:value="model.title" />
          </n-form-item-gi>
          <n-form-item-gi label="length：" path="length" span="4">
            <n-input v-model:value="model.length" />
          </n-form-item-gi>
          <n-form-item-gi span="16">
            <n-flex>
              <NButton secondary>
                重置
              </NButton>
              <NButton secondary type="info">
                查询
              </NButton>
            </n-flex>
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-card>

    <n-card class="hempClaw-content" size="small" title="麻爪">
      <template #header-extra>
        <n-flex>
          <NButton secondary size="small" strong type="primary" @click="handleAdd">
            <template #icon>
              <NIcon size="18">
                <div i="ri-add-line" />
              </NIcon>
            </template>
            新增
          </NButton>
          <NButton secondary size="small" type="error" @click="handleDelete">
            <template #icon>
              <NIcon size="18">
                <div i="ri-delete-bin-7-line" />
              </NIcon>
            </template>
            删除
          </NButton>
        </n-flex>
      </template>

      <n-alert :bordered="false" closable title="提示" type="info">
        <template #icon>
          😤
        </template>
        自适应表格
      </n-alert>

      <n-data-table
        v-model:checked-row-keys="checkedRowKeys"
        :bordered="false"
        :columns="tableColumns"
        :data="tableData"
        :loading="tableLoading"
        :row-props="rowProps"
        :style="{ flex: 1 }"
        flex-height
      />

      <n-pagination
        :default-page="page" :default-page-size="pageSize"
        :item-count="tableData.length" :page-sizes="[10, 20, 30, 40]" show-quick-jumper show-size-picker justify-center
        @update:page="handlePage" @update:page-size="handlePageSize"
      >
        <template #prefix="{ itemCount }">
          共 {{ itemCount }} 项
        </template>
      </n-pagination>
    </n-card>

    <n-modal
      v-model:show="showModal"
      :auto-focus="false"
      :segmented="{
        content: true,
      }"
      :style="{ width: '30%' }"
      :title="modalTitle"
      preset="card"
      size="small"
      @after-leave="handleAfterLeave"
    >
      <n-form
        ref="formRef"
        :model="model"
        :rules="rules"
        size="small"
      >
        <n-form-item label="title" path="title">
          <n-input v-model:value="model.title" />
        </n-form-item>
        <n-form-item label="length" path="length">
          <n-input v-model:value="model.length" />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-flex justify="end">
          <NButton secondary size="small" @click="showModal = false">
            取消
          </NButton>
          <NButton secondary size="small" type="info" @click="handleSubmit">
            确定
          </NButton>
        </n-flex>
      </template>
    </n-modal>
  </div>
</template>

<style lang="scss" scoped>
:deep(.n-card) {
  &.hempClaw-content {
    @apply flex-1;

    .n-card__content {
      @apply flex flex-col gap-y-8px;
    }
  }
}
</style>
